<?php

require __DIR__ . '/../bootstrap.php';
require_once __DIR__ . "/../auth.php";
require_once __DIR__ . "/loadUserListSimHelper.class.php";

$em = require __DIR__ . '/../example/em.php';

$auth = new \Auth\Auth($em);
$user = $auth->getUser();

$repo = $em->getRepository('Entity\User');
$qb = $em->createQueryBuilder();
$qb->select('u, g')
        ->from('Entity\User', 'u')
        ->innerJoin("u.group", "g")
        ->orderBy('u.root, u.lft', 'ASC')
        ->where($qb->expr()->gte('u.lft', ':ltf'))
        ->andWhere($qb->expr()->lte('u.rgt', ':rgt'))
        ->setParameter("ltf", $user->getLeft())
        ->setParameter("rgt", $user->getRight())
;


$tree = $repo->buildTreeArray($qb->getQuery()->getArrayResult());

/**
 * @param array $user
 * @param $em \Doctrine\ORM\EntityManager
 */
$getSims = function (array $user) use ($em) {
            $qb = $em->createQueryBuilder()->select('sim')->from('Entity\SimOwner', 'sim');
            $qb->where($qb->expr()->eq("sim.user", $user['id']))
                    ->andWhere($qb->expr()->eq("sim.state", ":state"))
                    ->setParameter("state", 1)
            ;
            return $qb->getQuery()->getResult();
        };

$result = array();
$count = 0;

$helper = new Helper($em);
$globalUser = $user;
//echo '<pre>';
////var_dump($helper->getDataBilling());
//echo '</pre>';
//exit();

$table = function (array $users) use (&$table, $getSims, &$result, &$count, $helper, &$globalUser) {
            foreach ($users as $user) {

                $sims = $getSims($user);
                if ($user['group']['id'] == 3) {
                    $group = '<i class="splashy-contact_green" style="margin-left:15px;"></i>%s';
                } else {
                    $group = '<i class="splashy-contact_blue"></i>%s';
                }
                $decode = (79988 + $user['id']) * 22;
                if (count($sims)) {
                    foreach ($sims as $sim) {
                        
                        /* @var $sim SimOvner */
                        
                        $maxDate = "00.00.0000";
                        $maxDateFillup = "00.00.0000";
                        $type = "--";
                        
                        $dataForSim = $helper->getDataForSim($sim->getSim()->getId());   
                        
                        if ($helper->isFiltering() && !$dataForSim) {
                            continue;
                        }
                        
                        if ($dataForSim) {
                            $maxDate = $dataForSim['maxdate'] ? Helper::dateFormat($dataForSim['maxdate']) : '';
                            $maxDateFillup = $dataForSim['maxdateFillup'] ? Helper::dateFormat($dataForSim['maxdateFillup']) : '';
                            $type = $dataForSim['paysystem'];

                            /*
                            echo '<pre>';
                            print_r($dataForSim);
                            echo '<pre>';
                            exit();
                            */
                        }



                        $iconUnbindNumber = '';
                        
                        if ($sim->getUser()->getId() == $globalUser->getId() && $globalUser->getParent() ) {
                            $iconUnbindNumber = '<a class="unbindnumber" id="' . $sim->getId() . '" href="javascript:void(0)"><i class="splashy-ticket_remove"></i></a>';
                        }
                        
                        $result['aaData'][] = array(
                            ++$count,
                            $sim->getSim()->getNumber(),
                            sprintf('<a href="index.php?page=user_profile&id=' . $decode . '">' . $group . '', $user['name'] . '</a>'),
                            $user['group']['name'],
                            "-",
                            '-',
                            "$maxDate",
                            "$maxDateFillup",
                            "$type",
                            '?',
                            $iconUnbindNumber
                        );
                    }
                } else {
                    $result['aaData'][] = array(
                        ++$count,
                        '',
                        sprintf('<a href="index.php?page=user_profile&id=' . $decode . '">' . $group . '', $user['name'] . '</a>'),
                        $user['group']['name'],
                        '',
                        '',
                        '',
                        '',
                        '',
                        '',
                        ''
                    );
                }
                if (count($user["__children"])) {
                    $table($user["__children"]);
                }
            }
        };

$table($tree);

echo json_encode($result);